<?php

namespace app\models;

use Yii;

/**
 * This is the model class for table "yyh_disease".
 *
 * @property int $id
 * @property string $name 名称
 * @property int|null $parent_id 上级病种
 * @property int|null $sort 排序
 * @property string $status 状态
 * @property string $createtime 创建时间
 * @property string $lastupdatetime 最后修改时间
 */
class Disease extends \yii\db\ActiveRecord
{
    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return 'yyh_disease';
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['name', 'status', 'createtime', 'lastupdatetime'], 'required'],
            [['parent_id', 'sort'], 'integer'],
            [['status'], 'string'],
            [['createtime', 'lastupdatetime'], 'safe'],
            [['name'], 'string', 'max' => 32],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'name' => '名称',
            'parent_id' => '上级病种',
            'sort' => '排序',
            'status' => '状态',
            'createtime' => '创建时间',
            'lastupdatetime' => '最后修改时间',
        ];
    }


    //得到树形结构的病种数据
    public static function getTreeData($where = '', $checked_ids_string = '')
    {
        $res = [];
        $children = [];
        if ($where == '') {
            $disease_objs = self::find()->orderBy('parent_id, sort asc, name, id')->asArray()->all();
        } else {
            $disease_objs = self::find()->where($where)->orderBy('parent_id, sort asc, name, id')->asArray()->all();
        }

        if($checked_ids_string != ''){
            $id_array = explode(",", $checked_ids_string);
            if(null != $id_array && count($id_array) > 0){
                foreach($id_array as $value_id){
                    foreach ($disease_objs as $i=>$d) {
                        if ((int)$d['id'] == (int)trim($value_id)) {
                            $disease_objs[$i]['checked'] = true;
                        }
                    }
                }
            }
        }
        
        foreach ($disease_objs as $d) {
            if ((int)$d['parent_id'] == 0) {
                $res[] = $d;
            } else {
                $children[$d['parent_id']][] = $d;
            }
        }
        foreach ($res as $i => $r) {
            if (null != $children[$r['id']]) {
                $res[$i]['children'] = $children[$r['id']];
            }
        }

        return $res;
    }

    public static function second_floor_key_value(){
        $array = Disease::getTreeData();
        $res = [];
        foreach($array as $root){
            foreach($root['children'] as $d){
                $res[$d['id']] = $d['name'];
            }
        }
        return $res;
    }
}
